package com.kgc.service.impl;

import com.kgc.dao.RoleDao;
import com.kgc.entity.MenuInfo;
import com.kgc.entity.Role;
import com.kgc.service.RoleService;
import com.kgc.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> getRoleList(Integer status) {
        if (status == 1) {
            return roleDao.getRoleListFroStatus();
        }
        return roleDao.getRoleList();
    }

    @Override
    public boolean saveRole(Role role) {
        int num = 0;
        if (role.getId() != null) {
            //修改
            num = roleDao.updateRole(role);
        } else {
            //新增
            num = roleDao.addRole(role.getRoleName());
        }
        if (num > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Role getRoleById(Integer id) {
        return roleDao.getRoleById(id);
    }

    @Override
    public int updateRoleStatus(Integer status, Integer id) {
        return roleDao.updateRoleStatus(status, id);
    }

    @Override
    public void delRole(Role[] roleList) {
        for (Role role : roleList) {
            roleDao.updateRoleStatus(0, role.getId());
        }
    }

    @Override
    public int countRoleByName(String roleName) {
        return roleDao.countRoleByName(roleName);
    }

    @Override
    public int updateRoleMenu(String checkedIds, Integer roleId) {
        roleDao.delMenuAll(roleId);//根据RoleId清楚 角色和菜单原有关系
        List<Integer> ids = JsonUtils.jsonToList(checkedIds, Integer.class);
        System.err.println(ids);
        int num = 0;
        for (Integer id : ids) {
            roleDao.addRoleMenu(id, roleId);//重新绑定角色和菜单
            num++;
        }
        return num;
    }

    @Override
    public void addRoleUserInfo(Integer roleId, Integer id) {
        roleDao.addRoleUserInfo(roleId, id);
    }

    @Override
    public Role getRoleInfoByUserId(Integer id) {
        return roleDao.getRoleByUserId(id);
    }

    @Override
    public int updateUserRole(Integer id, Integer roleId) {
        if (roleDao.getRoleByUserId(id) != null) {
            return roleDao.updateUserRole(id, roleId);
        }
        return roleDao.addRoleUserInfo(roleId, id);
    }
}
